from flask import Blueprint, request, jsonify
from models import db, TrainingExperience, TrainingAttachment
import os

training_bp = Blueprint('training', __name__)

# 获取某员工的所有培训经历
@training_bp.route('/api/employees/<int:employee_id>/training-experience', methods=['GET'])
def get_training_experiences(employee_id):
    experiences = TrainingExperience.query.filter_by(employee_id=employee_id).all()
    data = [
        {
            'id': exp.id,
            'employee_id': exp.employee_id,
            'course_name': exp.course_name,
            'organization': exp.organization,
            'start_date': exp.start_date,
            'end_date': exp.end_date,
            'certificate': exp.certificate,
            'created_at': exp.created_at,
            'updated_at': exp.updated_at
        } for exp in experiences
    ]
    return jsonify(data)

# 获取某员工的单条培训经历
@training_bp.route('/api/employees/<int:employee_id>/training-experience/<int:exp_id>', methods=['GET'])
def get_training_experience(employee_id, exp_id):
    exp = TrainingExperience.query.filter_by(id=exp_id, employee_id=employee_id).first()
    if not exp:
        return jsonify({'message': '未找到记录'}), 404
    return jsonify(exp.to_dict())

# 新增培训经历
@training_bp.route('/api/employees/<int:employee_id>/training-experience', methods=['POST'])
def add_training_experience(employee_id):
    data = request.json
    exp = TrainingExperience(
        employee_id=employee_id,
        course_name=data['course_name'],
        organization=data['organization'],
        start_date=data['start_date'],
        end_date=data['end_date'],
        certificate=data.get('certificate', '')
    )
    db.session.add(exp)
    db.session.commit()
    return jsonify({'message': '添加成功', 'id': exp.id}), 201

# 编辑培训经历
@training_bp.route('/api/employees/<int:employee_id>/training-experience/<int:exp_id>', methods=['PUT'])
def update_training_experience(employee_id, exp_id):
    exp = TrainingExperience.query.filter_by(id=exp_id, employee_id=employee_id).first()
    if not exp:
        return jsonify({'message': '未找到记录'}), 404
    data = request.json
    exp.course_name = data['course_name']
    exp.organization = data['organization']
    exp.start_date = data['start_date']
    exp.end_date = data['end_date']
    exp.certificate = data.get('certificate', '')
    db.session.commit()
    return jsonify({'message': '修改成功'})

# 删除培训经历
@training_bp.route('/api/employees/<int:employee_id>/training-experience/<int:exp_id>', methods=['DELETE'])
def delete_training_experience(employee_id, exp_id):
    exp = TrainingExperience.query.filter_by(id=exp_id, employee_id=employee_id).first()
    if not exp:
        return jsonify({'message': '未找到记录'}), 404
    db.session.delete(exp)
    db.session.commit()
    return '', 204

# 获取培训经历附件列表
@training_bp.route('/api/training-attachments/<int:training_id>', methods=['GET'])
def get_training_attachments(training_id):
    attachments = TrainingAttachment.query.filter_by(training_id=training_id).all()
    data = [
        {
            'id': att.id,
            'filename': att.filename,
            'filesize': att.filesize,
            'filetype': att.filetype,
            'description': att.description,
            'filepath': att.filepath,
            'upload_time': att.upload_time,
            'uploader': att.uploader
        } for att in attachments
    ]
    return jsonify({'data': data})

# 新增培训经历附件
@training_bp.route('/api/training-attachments/<int:training_id>', methods=['POST'])
def upload_training_attachment(training_id):
    if 'file' not in request.files:
        return jsonify({'error': 'No file part'}), 400
    file = request.files['file']
    if file.filename == '':
        return jsonify({'error': 'No selected file'}), 400
    description = request.form.get('description', '')
    uploader = request.form.get('uploader', '系统')
    # 保存文件
    filename = file.filename
    filepath = TrainingAttachment.get_path(filename=filename)
    file.save(filepath)
    # 创建附件记录
    attachment = TrainingAttachment(
        training_id=training_id,
        filename=filename,
        filesize=os.path.getsize(filepath),
        filetype=file.content_type,
        description=description,
        filepath=filepath,
        uploader=uploader
    )
    db.session.add(attachment)
    db.session.commit()
    return jsonify(attachment.to_dict()), 201

# 删除培训经历附件
@training_bp.route('/api/training-attachments/<int:training_id>/<int:attachment_id>', methods=['DELETE'])
def delete_training_attachment(training_id, attachment_id):
    attachment = TrainingAttachment.query.filter_by(id=attachment_id, training_id=training_id).first()
    if not attachment:
        return jsonify({'message': '未找到附件'}), 404
    # 删除物理文件
    if attachment.filepath and os.path.exists(attachment.filepath):
        os.remove(attachment.filepath)
    db.session.delete(attachment)
    db.session.commit()
    return '', 204

# 其他附件上传、下载、删除接口可参考证书或合同实现，后续可补充完善。 